package com.lingx.model.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.lingx.model.IContext;
import com.lingx.model.IPerformer;
import com.lingx.model.IScriptApi;
import com.lingx.utils.Utils;

/** 
 * @author www.lingx.com
 * @version 创建时间：2015年4月5日 下午4:11:05 
 * 类说明 
 */
@Scope("prototype")
@Component
public class DefaultPerformer implements IPerformer{
	static ScriptEngineManager sem = new ScriptEngineManager();
	@Resource
	private List<IScriptApi> apis;
	private ScriptEngine engine;
	
	@PostConstruct
	public void init() {
		engine = sem.getEngineByName("JavaScript");//Nashorn// sem.getEngineByName("graal.js");
		//System.out.println("=====================================================");
		//System.out.println("engine:"+engine);
		
	}
	
	public Object executeScript(String script, IContext context)
			throws Exception {
		for(IScriptApi api:apis){
			engine.put(api.getCode(),api.getApi());
		}
		if(context!=null){
			engine.put("CUser", context.getUserBean());
		}
		Object obj = null;
		try {
			obj = engine.eval(script);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getLocalizedMessage(),e);
		}
		return obj;
	}

	public void addParam(Map<String, Object> map) {
		if (map == null)
			return;
		for (String key : map.keySet()) {
			this.addParam(key, map.get(key));
		}
	}

	public void addParam(String key, Object val) {
		if(Utils.isNull(key))return;
		this.engine.put(key, val);
	}
	@Override
	public void initField(List<DefaultField> fields) {
		for(DefaultField field:fields) {
			this.engine.put(field.getCode(), "");
		}
	}


}
